/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.dao.jpa;

import com.jmooc.dao.CourseModuleDao;
import com.jmooc.entity.Course;
import com.jmooc.entity.CourseModule;
import com.jmooc.entity.CourseModule_;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author Group
 */
@Stateless
public class JpaCourseModuleDao implements CourseModuleDao {
    
    @PersistenceContext 
    private EntityManager em;

    @Override
    public List<CourseModule> getAllByCourse(Course course) {
        /*CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<CourseModule> query = cb.createQuery(CourseModule.class);
        Root<CourseModule> user = query.from(CourseModule.class);
        
        List<Predicate> predicates = new ArrayList<Predicate>();
        
        predicates.add(
            cb.equal(user.get(CourseModule_.id), course)
        );
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getResultList();*/
        return em.createQuery("SELECT cm from CourseModule cm WHERE cm.course = :c").setParameter("c", course).getResultList();
    }

    @Override
    public void create(CourseModule courseModule) {
        em.persist(courseModule);
    }

    @Override
    public CourseModule getById(Long id) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<CourseModule> query = cb.createQuery(CourseModule.class);
        Root<CourseModule> user = query.from(CourseModule.class);
        
        List<Predicate> predicates = new ArrayList<Predicate>();
        
        predicates.add(
            cb.equal(user.get(CourseModule_.id), id)
        );
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getSingleResult();
        //return (CourseModule) em.createQuery("SELECT c FROM CourseModule c WHERE c.id = :d").setParameter("d", id).getSingleResult();
    }

}
